export default (function() {
  class ImgZip {
    constructor({ width, height, type }) {
      this.file = null;
      this.img = new Image();
      this.reader = new FileReader();
      this.canvas = null;
      this.context = null;
      this.width = width || 200;
      this.height = height || 200;
      this.type = type || "blob";
    }

    // 初始化
    init(file) {
      if (!file) {
        throw new Error("请传入file文件");
      }
      this.file = file;
      !this.canvas && this.createCanvas();
      this.readFile();
      this.getBase64();
    }
    // 创建canvas
    createCanvas() {
      this.canvas = document.createElement("canvas");
      this.context = this.canvas.getContext("2d");
    }

    // 读取文件
    readFile() {
      if (this.file.type.indexOf("image") == 0) {
        this.reader.readAsDataURL(this.file);
      } else {
        throw new Error("读取的文件不是图片");
      }
    }

    // 获取base64
    getBase64() {
      this.reader.onload = e => {
        this.img.src = e.target.result;
      };
    }

    zipImg() {
      return new Promise((re, rj) => {
        this.img.onload = () => {
          // 图片原始尺寸
          let originWidth = this.img.width;
          let originHeight = this.img.height;
          // 最大尺寸限制
          let maxWidth = this.width;
          let maxHeight = this.height;
          // 目标尺寸
          var targetWidth = originWidth,
            targetHeight = originHeight;
          // 图片尺寸超过400x400的限制
          if (originWidth > maxWidth || originHeight > maxHeight) {
            if (originWidth / originHeight > maxWidth / maxHeight) {
              // 更宽，按照宽度限定尺寸
              targetWidth = maxWidth;
              targetHeight = Math.round(
                maxWidth * (originHeight / originWidth)
              );
            } else {
              targetHeight = maxHeight;
              targetWidth = Math.round(
                maxHeight * (originWidth / originHeight)
              );
            }
          }

          // canvas对图片进行缩放
          this.canvas.width = targetWidth;
          this.canvas.height = targetHeight;
          // 清除画布
          this.context.clearRect(0, 0, targetWidth, targetHeight);
          // 图片压缩
          this.context.drawImage(this.img, 0, 0, targetWidth, targetHeight);
          // canvas转为blob通过promise返回
          if (this.type === "blob") {
            this.canvas.toBlob(blob => {
              re(blob);
            }, this.file.type || "image/png");
          } else {
            // canvas转为base64返回
            let dataUrl = this.canvas.toDataURL("image/png");
            re(dataUrl);
          }
        };
      });
    }
  }
  return {
    zip(options) {
      let _class = null;
      if (!_class) {
        _class = new ImgZip(options);
      }
      _class.init(options.file);
      return _class.zipImg();
    }
  };
})();
